import {Work} from '../../../db/models/work';
import {sendError, sendSuccess} from "../../utils/responseHandler";
import {WorkSeeker} from "../../../db/models/work_seekers";
import jwt from "jsonwebtoken";
import {User} from "../../../db/models/user";
import sequelize from "../../../db";
import {QueryTypes} from "sequelize";

export default async function handler(req, res) {
    if (req.method === 'GET') {
        try {
            const token = req.headers.authorization?.split(' ')[1];  // Bearer token
            if (!token) {
                sendError(res, '没有提供Token', 401);
                return;
            }

            const decoded = jwt.verify(token, 'linweifeng123456789');
            const user = await User.findByPk(decoded.id);
            if (!user) {
                sendError(res, '用户未找到', 404);
                return;
            }

            const {minSalary, maxSalary, salaryUnit, queryWorkInput, queryConfirm,IsPerson} = req.query;

            console.log('131231',IsPerson)
            let conditions = [];
            if (queryConfirm && queryConfirm !== 'null') {
                conditions.push(`work_status = ${queryConfirm}`);
            }
            if (minSalary && minSalary !== 'null') {
                conditions.push(`min_salary >= ${minSalary}`);
            }
            if (maxSalary && maxSalary !== 'null') {
                conditions.push(`max_salary <= ${maxSalary}`);
            }
            if (salaryUnit && salaryUnit !== 'null') {
                conditions.push(`salary_unit = '${salaryUnit}'`);
            }
            if (queryWorkInput && queryWorkInput !== 'null') {
                conditions.push(`job_title LIKE '%${queryWorkInput}%'`);
            }

            let sql = `SELECT * FROM db_works`;
            if (IsPerson === '1') {
                sql += ` WHERE user_id = ${user.id}`;
                if (conditions.length > 0) {
                    sql += ` AND ${conditions.join(' AND ')}`;
                }
            }else{
                if (conditions.length > 0) {
                    sql += ` WHERE ${conditions.join(' AND ')}`;
                }
            }
            // let sql = `SELECT * FROM db_works WHERE user_id = ${user.id}`;


            const workList = await sequelize.query(sql, {
                type: QueryTypes.SELECT
            });

            const seekers = await WorkSeeker.findAll({
                where: {
                    user_id: user.id
                },
                raw: true
            })

            //这里的seekers是查询该用户报名了哪些岗位，里面每条数据都有work_id,并去与workList的id做比对，先找到有相等的，则在workList里面添加一个新字段叫applyed并赋值为1，表示该用户已经报名过了该岗位了,然后seekers的数据如果比对完了，那么剩下的appled的值就是0了
            const appliedWorkIds = seekers.map(seeker => seeker.work_id);

            // 遍历所有工作列表，更新每个工作的状态
            workList.forEach(work => {
                if (appliedWorkIds.includes(work.id)) {
                    // 如果在应聘列表中找到该工作ID，设置相应的status
                    const seekerData = seekers.find(seeker => seeker.work_id === work.id);
                    work.status = seekerData.status;
                } else {
                    // 如果没有找到，设置为未应聘状态
                    work.status = 0;  // 假设0代表未应聘
                }
            });

            sendSuccess(res, workList);
        } catch (error) {
            if (error.name === 'JsonWebTokenError') {
                sendError(res, '无效的Token', 401);
            } else if (error.name === 'TokenExpiredError') {
                sendError(res, 'Token已过期', 500);
            } else {
                sendError(res, error, 500);
            }
        }
    } else {
        res.setHeader('Allow', ['GET']);
        res.status(405).end('Method Not Allowed');
    }
}
